package net.jiastudy.biz.datasync.strategy.sdxm;

import net.jiastudy.biz.datasync.DataSyncStrategy;
import net.jiastudy.biz.datasync.SyncUtil;
import net.jiastudy.biz.datasync.strategy.sdxm.bean.DeptBean;
import net.jiastudy.biz.datasync.strategy.sdxm.bean.TeacherBean;
import net.jiastudy.biz.enums.DeptType;
import net.jiastudy.biz.sys.entity.Dept;
import net.jiastudy.biz.sys.service.DeptService;
import net.jiastudy.biz.user.service.UserService;
import net.jiastudy.core.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component("sdxmDataSyncStrategy")
public class SdxmDataSyncStrategyImpl implements DataSyncStrategy {
    private JdbcTemplate jdbc;

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private DeptService deptService;

    @Resource
    private AsyncTaskService asyncTaskService;

    @Resource
    UserService userService;

    @Override
    public boolean syncDepts() {
        if (SyncUtil.getTeacherSyncBatchCount() > 0) {
            throw new ServiceException("已经在同步数据，请稍后再试！");
        }
        SyncUtil.setTeacherSyncBatchCount(1);
        List<DeptBean> beans = findOriginalDepts();
        if (null == beans && beans.isEmpty()) {
            logger.info("校方部门数据为空，不需要同步");
            return true;
        }

        logger.info("总共有部门数：" + beans.size());
        int count = 0;
        for (DeptBean bean : beans) {
            try {
                Dept dept = new Dept();
                dept.setCode(bean.getDWH());
                dept.setName(bean.getDWMC());
                dept.setType(DeptType.other);
                deptService.createDept(dept);
                count++;
            } catch (ServiceException e) {
                logger.error(e.getMessage() + "名称为：" + bean.getDWMC() + "code为：" + bean.getDWH());
            }
        }

        logger.info("本次新增部门：" + count + "个");

        return true;
    }

    private List<DeptBean> findOriginalDepts() {
        String sql = "select * from MBGL_BMXXB";
        RowMapper<DeptBean> rowMapper = new BeanPropertyRowMapper<>(DeptBean.class);
        List<DeptBean> beans = this.getJdbc().query(sql, rowMapper);

        return beans;
    }

    @Override
    public boolean syncTeacher() {
        List<TeacherBean> beans = findOriginalTeachers();
        if (null == beans && beans.isEmpty()) {
            logger.info("校方教师数据为空，不需要同步");
            SyncUtil.decrTeacherSyncBatchCount();
            return true;
        }

        this.processTeachers(beans);

        return true;
    }

    private void processTeachers(List<TeacherBean> teachers) {
        int totalCount = teachers.size();
        int pageCount = 0;
        int pageSize = 100;
        if (totalCount % pageSize > 0) {
            pageCount = totalCount / pageSize + 1;
        } else {
            pageCount = totalCount / pageSize;
        }
        logger.info("总共有教师数：" + totalCount + "，分" + "pageCount" + "进行处理");
        SyncUtil.setTeacherSyncBatchCount(pageCount);
        for (int i = 1; i <= pageCount; i++) {
            List<TeacherBean> subList = null;
            if (totalCount % pageSize == 0) {
                subList = teachers.subList((i - 1) * pageSize, pageSize * (i));
            } else {
                if (i == pageCount) {
                    subList = teachers.subList((i - 1) * pageSize, totalCount);
                } else {
                    subList = teachers.subList((i - 1) * pageSize, pageSize * (i));
                }
            }
            if (null != subList) {
                logger.info("第" + i + "次异步处理，老师数" + subList.size());
                asyncTaskService.createTeachers(subList);
            }
        }
    }

    private List<TeacherBean> findOriginalTeachers() {
        String sql = "select * from MBGL_JGXXB";
        RowMapper<TeacherBean> rowMapper = new BeanPropertyRowMapper<>(TeacherBean.class);
        List<TeacherBean> beans = this.getJdbc().query(sql, rowMapper);

        return beans;
    }

    private JdbcTemplate getJdbc() {
        if (null != jdbc) {
            return jdbc;
        }

        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("oracle.jdbc.OracleDriver");
        dataSource.setUrl("jdbc:oracle:thin:@10.0.0.25:1521:orcl");
        dataSource.setUsername("mbgl");
        dataSource.setPassword("mbgl");

        jdbc = new JdbcTemplate(dataSource);

        return jdbc;
    }
}
